import FUtil from "./../io/io";
var path = require('path')

const JTem = {};
JTem.default = {};
JTem.default.rule = /#{{[ \t]*([@#]?)(\/?)([\w\W]*?)[ \t]*}}/g;

JTem.render = function (data, tem) {
   try{
    return  JTem.parseHTML(tem, data);
   }catch(err){
     //  console.log(err);
       
   }
};

JTem.parseHTML = function (tem, data) {
    //console.log(tem)
    var cursor = 0;
    var reExp = JTem.default.rule;
    var match = null;
    var $out = "var $out='';\n";
    $out += JTem.getAllParmsByData(data);//初始化所有变量   
    while ((match = reExp.exec(tem)) !== null) {
        // 开始标签  {{ 前的内容和结束标签 }} 后的内容 
        $out += parsehtml(tem.slice(cursor, match.index))
        // 开始标签  {{ 和 结束标签 }} 之间的内容
        // 每一次匹配完成移动指针
        //console.log("i"+match.index)
        $out += parsejs(match[3]);
        cursor = match.index + match[0].length;
    }
    //
    
    //console.log(tem.length - cursor)
    $out +=parsehtml(tem.substr(cursor, tem.length - cursor));
    $out += 'return $out;';

    function parsehtml(line) {
        // 单双引号转义，换行符替换为空格,去掉前后的空格        
        //.replace(/(^\s+)|(\s+$)/g, "")
       // line = line.replace(/('|")/g, '\\$1').replace(/\n/g, '\\n');

        line =  line.replace(/('|")/g, '\\$1').replace(/\n/g, '');
        //console.log(line);
        return '$out+="' + line + '";\n';
    }
    function parsejs(line) {
        var ss = /(^( )?(var|if|for|else|switch|case|break|{|}|;))(.*)?/g;

        return line.match(ss) ? line + '\n' : '$out+=' + line + ';\n';
       // return line.match(ss) ? line + '\n' : '$out+=' + line + ';';
    }

    $out=$out.replace(/[\r\t]/g, '');  
   // $out=$out.replace(/[\n]/g, '\\n');      
   try{
     return new Function($out).apply(data);
   }catch(err){
       console.log(err);
       var dd = new Date().getTime();
       FUtil.out($out,path.resolve(__dirname, './error/'+dd+".js"));
      //console.log($out);
       
   }
}

JTem.getAllParmsByData = function (data) {
    var $out = "";
    //console.log(data);
    for (var key in data) {      
        $out += "var " + key + "=this." + key + ";";
    }
    return $out;
}

export default JTem;